package demo.module_login.v;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;

import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import demo.module_login.R;
import demo.module_login.R2;
import demo.module_login.contract.ILoginContract;
import demo.module_login.p.LoginPresenter;
import library.base.mvp.presenter.event.BaseEvent;
import library.base.mvp.v.activity.BaseAppCompatActivity;
import library.common.util.NetworkUtil;
import library.common.util.ToastUtils;
import library.common.view.ClearEditText;
import library.common.view.PasswordEditText;
import module.common.RouterConfig;
import module.common.share.SharedManager;
import module.common.util.DialogUtils;

/**
 * @author Created by qiang.hou on 2018/11/30.
 * @version 1.0
 */
@Route(path = RouterConfig.login_LoginActivity)
public class LoginActivity extends BaseAppCompatActivity<LoginPresenter> implements ILoginContract.IView {
    @BindView(R2.id.icon_login_user)
    ImageView iconLoginUser;
    @BindView(R2.id.edit_input_user_phone)
    ClearEditText editInputUserPhone;
    @BindView(R2.id.icon_login_password)
    ImageView iconLoginPassword;
    @BindView(R2.id.edit_input_user_password)
    PasswordEditText editInputUserPassword;
    @BindView(R2.id.rl_password_login)
    RelativeLayout rlPasswordLogin;
    @BindView(R2.id.button_get_sms_code)
    Button buttonGetSmsCode;
    @BindView(R2.id.icon_login_sms)
    ImageView iconLoginSms;
    @BindView(R2.id.edit_input_sms_code)
    AppCompatEditText editInputSmsCode;
    @BindView(R2.id.rl_sms_login)
    RelativeLayout rlSmsLogin;
    @BindView(R2.id.button_login)
    Button buttonLogin;
    @BindView(R2.id.button_sms_login)
    TextView buttonSmsLogin;
    @BindView(R2.id.button_forget_password)
    TextView buttonForgetPassword;

    private boolean isTimerStart = false;
    private CountDownTimer timer;

    /**
     * 默认账号密码登录
     */
    private boolean isPassWordLogin = true;

    @OnClick({R2.id.button_login, R2.id.button_sms_login, R2.id.button_forget_password, R2.id.button_get_sms_code})
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.button_login) {
            mPresenter.login(
                    editInputUserPhone.getText().toString().trim(),
                    isPassWordLogin ? editInputUserPassword.getText().toString().trim() : Objects.requireNonNull(editInputSmsCode.getText()).toString().trim(),
                    isPassWordLogin);

        } else if (i == R.id.button_sms_login) {
            isPassWordLogin = !isPassWordLogin;
            refreshView();

        } else if (i == R.id.button_forget_password) {// goto forget password page
//                startActivity(new Intent(this, ForgetPasswordActivity.class));

        } else if (i == R.id.button_get_sms_code) {
            if (isPassWordLogin) return;
            setSmsCodeButtonEnable(false);
            mPresenter.sendSMSCode(editInputUserPhone.getText().toString().trim());
        }
    }

    @Override
    protected void initView() {
        editInputUserPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (isTimerStart) return;
                if (TextUtils.isEmpty(editInputUserPhone.getText().toString())) {
                    setSmsCodeButtonEnable(false);
                } else {
                    setSmsCodeButtonEnable(true);
                }
            }
        });
        initLoginAccount();
        if (!NetworkUtil.isNetworkAvailable(this)) {
            showNetErrorDialog();
        }
    }

    @Override
    protected void initProcess() {
        initLoginAccount();
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected int returnLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected boolean needEventBus() {
        return true;
    }

    @Override
    protected void onHandleMessage(BaseEvent event) {
        switch (event.actionTag) {
            case LoginPresenter.ACTION_PARAM_ERROR:
            case LoginPresenter.ACTION_CHECK_PHONE_REGISTER_ERROR:
                setSmsCodeButtonEnable(true);
                if (null != event.data2) {
                    ToastUtils.showToast(this, (String) event.data2, Toast.LENGTH_SHORT);
                } else if (null != event.data) {
                    ToastUtils.showToast(this, getResources().getString((Integer) event.data), Toast.LENGTH_SHORT);
                }
                break;
            case LoginPresenter.ACTION_GET_SMS_CODE_RESULT:
                setSmsCodeButtonEnable(true);
                if (null != event.data) {
                    if ((boolean) event.data) {
                        setSmsCodeCountdown();
                    } else {
                        ToastUtils.showToast(this, getResources().getString((Integer) event.data2), Toast.LENGTH_SHORT);
                    }
                }
                break;
            case LoginPresenter.ACTION_LOGIN_ERROR:
            case LoginPresenter.ACTION_USER_INFO_VERIFY_ERROR:
                if (null != event.data2) {
                    ToastUtils.showToast(this, (String) event.data2, Toast.LENGTH_SHORT);
                } else if (null != event.data) {
                    ToastUtils.showToast(this, getResources().getString((Integer) event.data), Toast.LENGTH_SHORT);
                }
                refreshView();
                break;
            case LoginPresenter.ACTION_LOGIN_SUCCESS:
                goMain();
                break;
            case LoginPresenter.ACTION_CHECK_PHONE_REGISTER_RESULT:
                setSmsCodeButtonEnable(true);
                boolean isUserRegistered = (boolean) event.data;
                if (!isUserRegistered) {
                    ToastUtils.showToast(this,
                            getResources().getString(R.string.text_toast_phone_is_not_registered), Toast.LENGTH_SHORT);
                }
                break;
        }
    }

    private final int GO_SET_NET_REQUEST_CODE = 1001;

    private void showNetErrorDialog() {
        DialogUtils.showNetworkErrorDialog(this, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 跳转到系统的网络设置界面
                Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                startActivityForResult(intent, GO_SET_NET_REQUEST_CODE);
                dialogInterface.dismiss();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (!NetworkUtil.isNetworkAvailable(LoginActivity.this)) {
                    ToastUtils.showToast(LoginActivity.this, getResources().getString(R.string.text_network_exception), Toast.LENGTH_SHORT);
                }
                dialogInterface.dismiss();
            }
        });
    }

    /**
     * 显示密码登录/验证码登录布局
     */
    private void refreshView() {
        rlPasswordLogin.setVisibility(isPassWordLogin ? View.VISIBLE : View.GONE);
        rlSmsLogin.setVisibility(isPassWordLogin ? View.GONE : View.VISIBLE);
        buttonSmsLogin.setText(isPassWordLogin ? R.string.text_button_sms_login : R.string.text_button_password_login);
        iconLoginUser.setImageResource(isPassWordLogin ? R.drawable.ic_login_user : R.drawable.ic_input_phone);
        editInputSmsCode.setText("");
        editInputUserPassword.setText("");
        editInputUserPhone.setHint(isPassWordLogin ? R.string.hint_login_input_user_name : R.string.hint_login_input_phone);
        editInputUserPhone.setInputType(isPassWordLogin ? InputType.TYPE_CLASS_TEXT : InputType.TYPE_CLASS_PHONE);
        if (!isPassWordLogin) {
            editInputUserPhone.setText("");
            editInputUserPhone.requestFocus();
        }
    }

    /**
     * 初始化设置上次的登录名
     */
    private void initLoginAccount() {
        String userName = SharedManager.getInstance().getValue(SharedManager.KEY_LOGIN_NAME, "");
        if (!TextUtils.isEmpty(userName)) {
            editInputUserPhone.setText(userName);
            editInputUserPassword.requestFocus();
        }
    }

    @Override
    public void setSmsCodeCountdown() {
        if (timer == null) {
            timer = new CountDownTimer(60000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    buttonGetSmsCode.setText(String.format(getString(R.string.text_second), millisUntilFinished / 1000));
                }

                @Override
                public void onFinish() {
                    buttonGetSmsCode.setText(R.string.text_get_sms_code);
                    setSmsCodeButtonEnable(true);
                    isTimerStart = false;
                }
            };
        }
        isTimerStart = true;
        setSmsCodeButtonEnable(false);
        timer.start();
    }

    @Override
    public void setSmsCodeButtonEnable(boolean b) {
        buttonGetSmsCode.setEnabled(b);
        buttonGetSmsCode.setBackgroundResource(b ? R.drawable.shap_for_login_button : R.drawable.shap_for_login_button_gray);
    }

    @Override
    public void goMain() {

    }
}
